package cn.sskxyz.mongodb.multi;

import java.util.Map;

import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;

public class MultiMongoMappingContext extends MongoMappingContext {

	private MongoMappingContext primary;

	private Map<String, MongoMappingContext> mappingContextMap;

	public MultiMongoMappingContext(MongoMappingContext primary, Map<String, MongoMappingContext> mappingContextMap) {
		this.primary = primary;
		this.mappingContextMap = mappingContextMap;
	}

	@Override
	public MongoPersistentProperty createPersistentProperty(Property property, MongoPersistentEntity<?> owner,
			SimpleTypeHolder simpleTypeHolder) {
		MongoLinkContext linkContext = MongoDbLinkHolder.get();
		if (linkContext == null || linkContext.getLink() == null) {
			return primary.createPersistentProperty(property, owner, simpleTypeHolder);
		}

		MongoMappingContext context = mappingContextMap.get(linkContext.getLink());
		return context.createPersistentProperty(property, owner, simpleTypeHolder);
	}

	@Override
	public boolean isAutoIndexCreation() {
		MongoLinkContext linkContext = MongoDbLinkHolder.get();
		if (linkContext == null || linkContext.getLink() == null) {
			return primary.isAutoIndexCreation();
		}

		MongoMappingContext context = mappingContextMap.get(linkContext.getLink());
		return context.isAutoIndexCreation();
	}

}
